package com.example.weatherreport;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.weatherreport.city_manager.CityManagerActivity;
import com.example.weatherreport.db.DBManager;
import com.example.weatherreport.location.LocationCallback;
import com.example.weatherreport.location.MyLocationListener;
import com.example.weatherreport.location.NowCityUtil;
import com.example.weatherreport.utils.SpUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, LocationCallback {
    //添加和更多，计数器，主界面
    ImageView addCityIv,moreIv,location;

    TextView fragTop_tv_city;
    LinearLayout pointLayout;
    RelativeLayout outLayout;
    ViewPager mainVp;
    // ViewPager的数据源
    List<Fragment> fragmentList;
    // 表示需要显示的城市的集合
    List<String> cityList;
    // 表示ViewPager的页数指数器显示集合
    List<ImageView> imgList;

    private CityFragmentPagerAdapter adapter;

    // 交换背景图片
    private SharedPreferences pref;
    private int bgNum;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 启动前请求定位权限
        registerIntent();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

//        // 调用定位
//        initLocation();
//        requestPermission();

        addCityIv = findViewById(R.id.main_iv_add);
        moreIv = findViewById(R.id.main_iv_more);

        location = findViewById(R.id.main_iv_location);

        pointLayout = findViewById(R.id.main_layout_point);
        outLayout = findViewById(R.id.main_out_layout);
        exchangeBg();//一进到页面调用交换背景函数
        fragTop_tv_city = findViewById(R.id.fragTop_tv_city);
        mainVp = findViewById(R.id.main_vp);

        // 添加点击事件
        addCityIv.setOnClickListener(this);
        moreIv.setOnClickListener(this);

        location.setOnClickListener(this);

        test();
    }

    private void test() {
        fragmentList = new ArrayList<>();
        // 获取db中city表的数据
        cityList = DBManager.queryAllCityName();
        imgList = new ArrayList<>();

        if (cityList.size() == 0) { // 默认添加北京城市
            cityList.add("北京");
//            cityList.add("上海");
        }
        /* 搜索界面点击跳转此界面，会传值，此处获取一下*/
        try {
            Intent intent = getIntent();
            String city = intent.getStringExtra("city");
            if (!cityList.contains(city) && !TextUtils.isEmpty(city)) {
                cityList.add(city);
            }
        } catch (Exception e) {
            Log.i("wyu", "程序出现问题了！！");
        }

        // 初始化ViewPager页面的方法
        initPager();
        adapter = new CityFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        mainVp.setAdapter(adapter);
        // 创建小圆点指示器
        initPoint();
        // 设置最后一个城市信息
        mainVp.setCurrentItem(fragmentList.size() - 1);

        // 设置ViewPager页面监听
        setPagerListener();
    }

    private void initPoint() {
//        创建小圆点 ViewPager页面指示器的函数
        for (int i = 0; i < fragmentList.size(); i++) {
            ImageView pIv = new ImageView(this);
            pIv.setImageResource(R.mipmap.a1);
            pIv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) pIv.getLayoutParams();
            lp.setMargins(0, 0, 20, 0);
            imgList.add(pIv);
            pointLayout.addView(pIv);
        }
        imgList.get(imgList.size() - 1).setImageResource(R.mipmap.a2);
    }

    private void initPager() {
        /* 创建Fragment对象，添加到ViewPager数据源当中*/
        for (int i = 0; i < cityList.size(); i++) {
            CityWeatherFragment cwFrag = new CityWeatherFragment();
            Bundle bundle = new Bundle();
            bundle.putString("city", cityList.get(i));

            // testing
            fragTop_tv_city.setText(cityList.get(i).trim());

            cwFrag.setArguments(bundle);
            fragmentList.add(cwFrag);

        }
    }


    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.main_iv_add:
                intent.setClass(this, CityManagerActivity.class);
                break;
            case R.id.main_iv_more:
                intent.setClass(this, MoreActivity.class);
                break;
            case R.id.main_iv_location:
                // 调用定位
                initLocation();
                requestPermission();

                return;
        }
        startActivity(intent);
    }

    private void setPagerListener() {
        /* 设置监听事件*/
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < imgList.size(); i++) {
                    imgList.get(i).setImageResource(R.mipmap.a1);
                }
                //System.out.println(cityList);
                imgList.get(position).setImageResource(R.mipmap.a2);
                fragTop_tv_city.setText(cityList.get(position).trim());
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }


    /* 当页面重写加载时会调用的函数，这个函数在页面获取焦点之前进行调用，此处完成ViewPager页数的更新*/
    @Override
    protected void onRestart() {
        super.onRestart();
        // 获取数据库当中还剩下的城市集合
        List<String> list = DBManager.queryAllCityName();
        if (list.size() == 0) {
            list.add("北京"); //删光城市后，最后的底线
        }
        cityList.clear();    //重写加载之前，清空原本数据源
        cityList.addAll(list);

        // 剩余城市也要创建对应的fragment页面
        fragmentList.clear();
        initPager();
        adapter.notifyDataSetChanged();//提示adapter更新

        // 页面数量发生改变，指示器的数量也会发生变化，重写设置添加指示器
        imgList.clear();
        pointLayout.removeAllViews();   //将布局当中所有元素全部移除
        initPoint();
        mainVp.setCurrentItem(fragmentList.size() - 1);
    }


    // 交换壁纸的函数
    public void exchangeBg() {
        pref = getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
            case 99:
                try {
                    //从缓存取出图片
                    Drawable photo1 = SpUtils.getDrawableByKey(this, "photo");
                    outLayout.setBackground(photo1);

                    break;
                }
                catch (Exception e)
                {
                    //如果上面失败了，就设置默认的
                    e.printStackTrace();
                    Toast.makeText(this, "加载壁纸失败，源文件可能已经被删除，挪动。", Toast.LENGTH_SHORT).show();
                    outLayout.setBackgroundResource(R.mipmap.bg2);
                    break;
                }
        }
    }


    // 定位
    public LocationClient mLocationClient = null;
    private final MyLocationListener myListener = new MyLocationListener();

    /**
     * 初始化定位
     */
    private void initLocation() {
        LocationClient.setAgreePrivacy(true);
        try {
            mLocationClient = new LocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mLocationClient != null) {
            myListener.setCallback(this);
            //注册定位监听
            mLocationClient.registerLocationListener(myListener);
            LocationClientOption option = new LocationClientOption();
            //如果开发者需要获得当前点的地址信息，此处必须为true
            option.setIsNeedAddress(true);
            //可选，设置是否需要最新版本的地址信息。默认不需要，即参数为false
            option.setNeedNewVersionRgc(true);
            //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
            mLocationClient.setLocOption(option);
        }
    }


    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        double latitude = bdLocation.getLatitude();    //获取纬度信息
        double longitude = bdLocation.getLongitude();    //获取经度信息
        float radius = bdLocation.getRadius();    //获取定位精度，默认值为0.0f
        String coorType = bdLocation.getCoorType();
        //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
        int errorCode = bdLocation.getLocType();//161  表示网络定位结果
        //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
        String addr = bdLocation.getAddrStr();    //获取详细地址信息
        String country = bdLocation.getCountry();    //获取国家
        String province = bdLocation.getProvince();    //获取省份
        String city = bdLocation.getCity();    //获取城市
        String district = bdLocation.getDistrict();    //获取区县
        String street = bdLocation.getStreet();    //获取街道信息
        String locationDescribe = bdLocation.getLocationDescribe();    //获取位置描述信息

        List<String> strings = DBManager.queryAllCityName();
        String s = province+" "+city;

        if(province==null||city==null){
            Toast.makeText(this, "定位有时间间隔，请稍后重试", Toast.LENGTH_SHORT).show();

        } else if (NowCityUtil.getNowCity()!=s){
            Toast.makeText(this, "当前定位："+s, Toast.LENGTH_SHORT).show();
            //Toast.makeText(this, "s:"+s, Toast.LENGTH_SHORT).show();
            //Toast.makeText(this, "NowCityUtil:"+NowCityUtil.getNowCity(), Toast.LENGTH_SHORT).show();
            NowCityUtil.setNowCity(s);
            if (isContainCity(strings,NowCityUtil.getNowCity())){
                //Toast.makeText(this, "城市已存在", Toast.LENGTH_SHORT).show();
            }else {
                //Toast.makeText(this, "当前定位："+s, Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("city", NowCityUtil.getNowCity());

                startActivity(intent);
            }
        }
    }

    private boolean isContainCity(List<String> strings,String s){
        for (int i = 0; i < strings.size(); i++) {
            if (s.indexOf(strings.get(i))>0) {
                return true;
            }
        }
        return false;
    }

    // 启动定位
    private void startLocation() {
        if (mLocationClient != null) {
            mLocationClient.start();
        }
    }

    //权限数组
    private final String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求权限意图
    private ActivityResultLauncher<String[]> requestPermissionIntent;

    private void registerIntent() {
        //请求权限意图
        requestPermissionIntent = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> {
            boolean fineLocation = Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_FINE_LOCATION));
            boolean writeStorage = Boolean.TRUE.equals(result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE));
            if (fineLocation && writeStorage) {
                //权限已经获取到，开始定位
                startLocation();
            }
        });
    }
    private void requestPermission() {
        //因为项目的最低版本API是23，所以肯定需要动态请求危险权限，只需要判断权限是否拥有即可
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //开始权限请求
                requestPermissionIntent.launch(permissions);
                return;
            }
        }
        //开始定位
        startLocation();
    }


}